package com.panopset.flywheel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Command to handle normal text entry.
 *
 * @author Karl Dinwiddie
 */
public class CommandText extends Command {

    /**
     * Command text.
     */
    private String text;

    /**
     * Command Text constructor.
     *
     * @param template
     *            Template this command was declared in.
     * @param params
     *            Params.
     */
    public CommandText(final Template template, final String params) {
        super(template);
        assert params != null;
        this.text = params;
    }

    @Override
    public final String getDescription() {
        StringReader sr = new StringReader(text);
        BufferedReader br = new BufferedReader(sr);
        try {
            String s = br.readLine();
            if (s == null) {
                return "";
            }
            return s;
        } catch (IOException e) {
            return e.getMessage();
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                Logger.getLogger(CommandText.class.getName()).log(Level.SEVERE,
                        null, ex);
            }
        }
    }

    @Override
    public final void resolve(final StringWriter sw) {
        String rtn = text;
        if (!getTemplate().getFlywheel().isReplacementsSuppressed()) {
            for (String[] s : getTemplate().getFlywheel().getReplacements()) {
                rtn = rtn.replace(s[0], s[1]);
            }
        }
        sw.append(rtn);
    }
}
